//
//  APUserPageViewController.m
//  AqualPolo
//
//  Created by dong on 2024/5/12.
//

#import "APUserPageViewController.h"
#import "APUserPageWorksViewCell.h"
#import "APDiscoveryDataManager.h"
#import "APBottomMenuViewController.h"
#import "APWorksDetailViewController.h"
#import "APUserDataManager.h"
@interface APUserPageViewController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UIImageView *avatarImageView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UIButton *followButton;
@property (nonatomic, strong) UIImageView *ballImageView;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@end

@implementation APUserPageViewController

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        layout.sectionInset = UIEdgeInsetsMake(12, 15, 15, 15);
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = UIColor.clearColor;
        [_collectionView registerClass:[APUserPageWorksViewCell class] forCellWithReuseIdentifier:@"item"];
    }
    return _collectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadNaviBar];
    self.naviBar.moreButton.hidden = false;
    [self loadBackground:@"discovery_list_bg"];
    [self initUI];
    [self refreshData];
}

- (void)refreshData{
    WS(ws);
    [self.view ShowProgress];
    [self.dataArray removeAllObjects];
   APBroadcasterModel *userModel = [[APUserDataManager shareInstance] searchUserByUserId:_userId];
    self.followButton.hidden = userModel.isFriend;
    [[APDiscoveryDataManager shareInstance] loadData:^{
        for (APWorksModel *model in [APDiscoveryDataManager shareInstance].dataArray) {
           APBroadcasterModel *userModel = [[APUserDataManager shareInstance] searchUserByUserId:model.userId];
            if ([userModel.userId isEqualToString:ws.userId]) {
                [ws.dataArray addObject:model];
            }
        }
        [ws.collectionView reloadData];
        [ws.view removeProgress];
    }];
}


- (void)naviViewMoreButtonDidClick{
    APBottomMenuViewController *menuVC = [[APBottomMenuViewController alloc] init];
    [menuVC setCallBack:^(NSInteger index) {
        if (index == 1) {
            [self.navigationController popViewControllerAnimated:true];
        }else{
            [self refreshData];
        }
    }];
    menuVC.userId =_userId;
    [self.tabBarController presentViewController:menuVC animated:true completion:nil];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width =( collectionView.frame.size.width - 40) * 0.5;
    return CGSizeMake(width, 204);
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    APUserPageWorksViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    [cell.topButton addTarget:self action:@selector(moreButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    APWorksModel *model = [self.dataArray objectAtIndex:indexPath.item];
    cell.imageView.image = [UIImage imageNamed:model.cover];
    [cell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:model.avatar]];
    cell.titleLabel.text = model.title;
    cell.nameLabel.text = model.nickname;
    cell.upvoteButton.selected = model.upvote;
    [cell.upvoteButton addTarget:self action:@selector(upvoteButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    APWorksModel *model = [self.dataArray objectAtIndex:indexPath.item];
    APWorksDetailViewController *detailVC = [[APWorksDetailViewController alloc] init];
    detailVC.worksModel = model;
    [self.navigationController pushViewController:detailVC animated:true];
}

- (void)followButtonDidClick:(UIButton *)sender{
    [self.view ShowProgress];
    WS(ws);
    [[APUserDataManager shareInstance] follow:_userId result:^(_Bool success, NSString * _Nonnull msg) {
        [self.view removeProgress];
        if (success) {
            sender.hidden = true;
            [ws.view ShowProgressOnlyLabel:msg];
        }else{
            [self dismissViewControllerAnimated:true completion:nil];
        }
    }];
}

- (void)moreButtonDidClick:(UIButton *)sender{
    APBottomMenuViewController *menuVC = [[APBottomMenuViewController alloc] init];
    [menuVC setCallBack:^(NSInteger index) {
        if (index == 1) {
            [self.navigationController popViewControllerAnimated:true];
        }else{
            [self refreshData];
        }
    }];
    menuVC.userId =_userId;
    [self.tabBarController presentViewController:menuVC animated:true completion:nil];
}

- (void)upvoteButtonDidClick:(UIButton *)sender{
    CGPoint point = sender.center;
    point = [self.collectionView convertPoint:point fromView:sender.superview];
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
    APWorksModel *model = self.dataArray[indexPath.item];
    model.upvote = !model.upvote;
    [self.collectionView reloadData];
    [[APDiscoveryDataManager shareInstance] updateWorks:model.worksId];
}


- (void)initUI{
    
    APBroadcasterModel *userModel = [[APUserDataManager shareInstance] searchUserByUserId:_userId];
    _avatarImageView = [[UIImageView alloc] init];
    _avatarImageView.layer.cornerRadius = 80;
    _avatarImageView.layer.masksToBounds = true;
    [_avatarImageView sd_setImageWithURL:[NSURL URLWithString:userModel.avatar]];
    [self.view addSubview:_avatarImageView];
    [_avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.naviBar.mas_bottom).offset(12);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(160, 160));
    }];
    _nameLabel = [[UILabel alloc] init];
    _nameLabel.text = userModel.nickname;
    _nameLabel.textColor = [UIColor whiteColor];
    _nameLabel.font = [UIFont systemFontOfSize:18];
    _nameLabel.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:_nameLabel];
    [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_avatarImageView.mas_bottom).offset(27);
        make.height.mas_equalTo(24);
        make.centerX.equalTo(self.view).offset(-16);
    }];
    UIImageView *iconImageView = [[UIImageView alloc] init];
    iconImageView.image = [UIImage imageNamed:@"ball_1"];
    [self.view addSubview:iconImageView];
    self.ballImageView = iconImageView;
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_nameLabel.mas_right).offset(8);
        make.centerY.equalTo(_nameLabel);
        make.size.mas_equalTo(CGSizeMake(24, 24));
    }];
    
    _followButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_followButton addTarget:self action:@selector(followButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    _followButton.backgroundColor = LYRGBColor(87, 61, 255);
    _followButton.layer.cornerRadius = 8;
    _followButton.layer.masksToBounds = true;
    [_followButton setTitle:@"Follow" forState:UIControlStateNormal];
    _followButton.titleLabel.font = [LYFont fontWithSize:18 fontName:LYFontNamepfb];
    [self.view addSubview:_followButton];
    [_followButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_nameLabel.mas_bottom).offset(19);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(120, 36));
    }];
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_followButton.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
}


@end
